/*
 * @Author: zxc
 * @Date: 2020-08-18 14:50:33
 * @LastEditTime: 2020-09-11 16:33:38
 * @LastEditors: zxc
 * @Description: 颜色选择组件
 */
import React, { memo, useMemo, useState, useCallback } from "react";
import {
  SketchPicker,
  GithubPicker,
  PhotoshopPicker,
  ChromePicker,
} from "react-color";
import { useDebounce } from "../../hooks/useDebounce";
import { Popover } from "antd";
import "./index.less";

interface IProps {
  themeColor: string;
  onChangeComplete: (color: string) => void;
  type?: string;
  position?: string;
  small?: boolean;
}

const pickers: {
  [key: string]: React.ReactNode;
} = {
  chrome: ChromePicker,
  github: GithubPicker,
  sketch: SketchPicker,
  photoshop: PhotoshopPicker,
};

const PickColor: React.FC<IProps> = (props) => {
  const {
    type = "chrome",
    position = "bottom",
    themeColor,
    onChangeComplete,
  } = props;
  const [displayColorPicker, setDisplayColorPicker] = useState(false);
  const [color, setColor] = useState(themeColor);
  const Picker: any = pickers[type];

  const handleChange = useDebounce((color: any, event: any) => {
    onChangeComplete(color.hex);
    setColor(color.hex);
  },100);

  //改色
  const handleChangeComplete = (color: any) => {
    onChangeComplete(color.hex);
    setColor(color.hex);
  };

  //关闭选色框
  const handleClosePicker = useCallback(() => {
    setDisplayColorPicker(false);
    // eslint-disable-next-line
  }, [displayColorPicker]);

  // 展示色块的点击
  // 这里使用useCallback的目前是做一层优化，对函数进行缓存，防止每一次进入都要渲染一次这个函数，这个可以只根据displayColorPicker这个值来更新这个函数
  const handleClick = useCallback(() => {
    setDisplayColorPicker(!displayColorPicker);
  }, [displayColorPicker]);

  //同样做优化，使用了useMemo
  const { swatch, picker } = useMemo(() => {
    const styles: any = {
      wrapper: {
        position: "inherit",
        zIndex: 100,
      },
    };
    if (position === "top") {
      styles.wrapper.transform = "translateY(-100%)";
      styles.wrapper.paddingBottom = 8;
    }

    const swatch = (
      <Popover content="更换主题色">
        <div
          className="swatch"
          onClick={handleClick}
          style={{
            background: color,
          }}
        >
          <div className="swatch-color"></div>
        </div>
      </Popover>
    );

    const picker = displayColorPicker ? (
      <div className="popover">
        <div className="cover" onClick={handleClosePicker} />
        <div style={styles.wrapper}>
          <Picker
            {...props}
            color={color}
            onChange={handleChange}
            onChangeComplete={handleChangeComplete}
          />
        </div>
      </div>
    ) : null;

    return {
      swatch,
      picker,
    };
    // eslint-disable-next-line
  }, [position, handleClick, color, displayColorPicker, handleChangeComplete]);

  return (
    <div className="pick-color">
      {picker}
      {swatch}
    </div>
  );
};
export default memo(PickColor);
